<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <el-row style="align-items: center">
      <el-col
        @dblclick="handleStartEdit"
        style="display: flex; align-items: center"
        :span="16"
      >
        <el-avatar :size="30" :src="iconPic" shape="circle" />

        <span v-if="!isEdit">{{ module.name }}</span>
        <input
          ref="moduleEditor"
          maxlength="15"
          v-else
          class="el-input"  
          :value="module.name"
          size="default"
          @blur="handleUpdate"
          @keyup.enter="handleUpdate"
        />
      </el-col>
      <el-col :span="8">
        <el-button
          type="primary"
          size="default"
          :icon="EditPen"
          @click="handleStartEdit"
        ></el-button>
        <el-button
          type="danger"
          size="default"
          :icon="Delete"
          @click="handleDelete(module)"
        ></el-button>
      </el-col>
    </el-row>
  </el-card>
</template>

<script setup lang="ts">
import type { SunnyModule } from "@/types/sunnyModule/type";
import { ElMessage, ElMessageBox } from "element-plus";
import { EditPen, Delete } from "@element-plus/icons-vue";
import { ref, watch } from "vue";
import { nextTick } from "vue";
import { computed } from "vue";
const props = defineProps<{ module: SunnyModule }>();
const emit = defineEmits(["updateModule", "deleteModule"]);

const webPic = ref(new URL("@/assets/img/web.png", import.meta.url).href);
const apiPic = ref(new URL("@/assets/img/api.png", import.meta.url).href);
const iconPic = computed(() => {
  return props.module.type === "web" ? webPic.value : apiPic.value;
});

//编辑功能
const isEdit = ref(false);
//编辑输入框的ref模板对象
const moduleEditor = ref<HTMLInputElement>();
function handleDelete(module: SunnyModule) {
  ElMessageBox.confirm(`确认删除模块${module.name}吗？这会删除其下的所有用例`)
    .then(() => {
      emit("deleteModule", module);
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
}

/**
 * 开始编辑，同时完成聚焦
 */
function handleStartEdit() {
  isEdit.value = true;

  //   获取元素完成聚焦
  //  由于vue中的dom元素更新不是实时的，要等到响应式数据的操作完成之后再刷新dom，所以不能直接写dom元素的控制
  //   moduleEditor.value.focus();
  //用延时执行可以实现，最好的办法还是nextTick
  //   setTimeout(() => {
  //     moduleEditor.value.focus();
  //   }, 300);
  nextTick(() => {
    if (!moduleEditor.value) return;
    moduleEditor.value.focus();
  });
}

/**
 * 不能直接传module了
 * @param module
 */
function handleUpdate(event: any) {
  if (event.target.value.length < 2) {
    ElMessage.warning("模块名称请设置超过两位字符！");
    event.target.value = props.module.name;
    return;
  }
  emit("updateModule", event.target.value);
  //编辑完成，切换到展示元素
  isEdit.value = false;
}
</script>

<style scoped>
.el-button {
  padding: 5px;
  margin-left: 3px;
  margin-right: 0px;
}
</style>
